# config_loader.py
import yaml
import os
import sys
import random

# 系统前缀，用于多开区分状态
system = "a_"

# 数据库配置
mongo_url = "mongodb://localhost:27017"
mango_db = "xhs"
mango_source = "source"
mango_send = "send"

# 查询评论时间n分钟内的数据
data_time_limit = 30000000
# 每次查询数量限制
data_count_limit = 100
# 数据库查询时间间隔（单位秒）
data_interval = 10

# 扫描在线设备时间间隔
device_scan_sleep = 10

# 私信内容
message = []
# 打开app睡眠时间（单位秒）
app_start_sleep = 6
# 其他每一步骤睡眠时间（单位秒）
app_other_sleep = 2

un_read_notice = 3

home_sleep = 1000


#
# def resource_path(relative_path):
#     """兼容打包和未打包两种模式"""
#     try:
#         # 打包后临时文件夹路径
#         base_path = sys._MEIPASS
#     except AttributeError:
#         # 脚本运行时所在目录
#         base_path = os.path.dirname(os.path.abspath(__file__))
#
#     return os.path.join(base_path, relative_path)
#
# config_path = resource_path("config.yaml")
#
# with open(config_path, 'r', encoding='utf-8') as f:
#     data = yaml.safe_load(f)
#


def get_config_path(filename="config.yaml"):
    """
    获取配置文件的绝对路径，兼容打包后运行（PyInstaller）和源码运行。
    """
    if hasattr(sys, '_MEIPASS'):
        # PyInstaller 打包后的路径
        base_path = sys._MEIPASS
    else:
        # 源码运行路径，返回项目根目录
        base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
    return os.path.join(base_path, filename)


def load_config(filename="config/config.yaml"):
    """
    加载 YAML 配置文件内容
    :param filename: 文件名
    :return: dict 格式配置内容
    """
    config_path = get_config_path(filename)
    with open(config_path, 'r', encoding='utf-8') as f:
        return yaml.safe_load(f)


def save_config(config_data, filename="config/config.yaml"):
    """
    保存 dict 格式的配置数据到 YAML 文件
    :param config_data: 要保存的配置字典
    :param filename: 配置文件路径
    """
    config_path = get_config_path(filename)
    with open(config_path, 'w', encoding='utf-8') as f:
        yaml.dump(config_data, f, allow_unicode=True, sort_keys=False)


# 配置内容作为常量导出
data = load_config()

system = data.get('system')
mongo_url = data.get('mongo_url')
mango_db = data.get('mango_db')
mango_source = data.get('mango_source')
mango_device = data.get('mango_device')
mango_send = data.get('mango_send')
data_time_limit = data.get('data_time_limit')
data_count_limit = data.get('data_count_limit')
data_interval = data.get('data_interval')
device_scan_sleep = data.get('device_scan_sleep')
message = data.get('message', [])
app_start_sleep = data.get('app_start_sleep')
app_other_sleep = data.get('app_other_sleep')
un_read_notice = data.get("un_read_notice")
home_sleep = data.get("home_sleep")


def get_app_other_sleep():
    return app_other_sleep + random.uniform(1, 2)


_index = 0  # 当前索引


def get_next_message():
    global _index
    if not message:
        return None  # 空列表处理
    msg = message[_index]
    _index = (_index + 1) % len(message)  # 循环索引
    return msg
